<template>
  <view class="bg-[#f5f5f5] min-h-screen">
    <!-- 头部 -->
    <PageHeader title="候选人管理" :showBack="true" />

    <!-- 统计信息 -->
    <view
      class="bg-white rounded-[20rpx] mx-[30rpx] mt-[30rpx] p-[40rpx] shadow-md"
    >
      <view class="grid grid-cols-2 md:grid-cols-4 gap-[20rpx]">
        <view class="text-center p-[20rpx]">
          <text
            class="text-[48rpx] font-bold text-[#1976d2] block mb-[10rpx]"
            >{{ totalCount }}</text
          >
          <text class="text-[26rpx] text-[#666]">总候选人</text>
        </view>
        <view class="text-center p-[20rpx]">
          <text
            class="text-[48rpx] font-bold text-[#f57c00] block mb-[10rpx]"
            >{{ pendingCount }}</text
          >
          <text class="text-[26rpx] text-[#666]">待处理</text>
        </view>
        <view class="text-center p-[20rpx]">
          <text
            class="text-[48rpx] font-bold text-[#388e3c] block mb-[10rpx]"
            >{{ invitedCount }}</text
          >
          <text class="text-[26rpx] text-[#666]">已邀请</text>
        </view>
        <view class="text-center p-[20rpx]">
          <text
            class="text-[48rpx] font-bold text-[#d32f2f] block mb-[10rpx]"
            >{{ rejectedCount }}</text
          >
          <text class="text-[26rpx] text-[#666]">已拒绝</text>
        </view>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view
      class="bg-white rounded-[20rpx] mx-[30rpx] mt-[30rpx] p-[30rpx] shadow-md"
    >
      <view class="flex flex-wrap gap-[20rpx]">
        <!-- 职位筛选 -->
        <view class="flex-1 min-w-[200rpx]">
          <view
            class="w-full p-[20rpx] border-2 border-[#ddd] rounded-[12rpx] text-[26rpx] bg-white box-border cursor-pointer flex items-center justify-between"
            @click="showPositionPicker = true"
          >
            <text :class="selectedPosition ? 'text-[#333]' : 'text-[#999]'">
              {{ selectedPosition || "所有职位" }}
            </text>
            <IconFont name="arrow-down" class="text-[24rpx] text-[#999]" />
          </view>
        </view>

        <!-- 状态筛选 -->
        <view class="flex-1 min-w-[200rpx]">
          <view
            class="w-full p-[20rpx] border-2 border-[#ddd] rounded-[12rpx] text-[26rpx] bg-white box-border cursor-pointer flex items-center justify-between"
            @click="showStatusPicker = true"
          >
            <text :class="selectedStatus ? 'text-[#333]' : 'text-[#999]'">
              {{ selectedStatus || "所有状态" }}
            </text>
            <IconFont name="arrow-down" class="text-[24rpx] text-[#999]" />
          </view>
        </view>

        <!-- 来源筛选 -->
        <view class="flex-1 min-w-[200rpx]">
          <view
            class="w-full p-[20rpx] border-2 border-[#ddd] rounded-[12rpx] text-[26rpx] bg-white box-border cursor-pointer flex items-center justify-between"
            @click="showSourcePicker = true"
          >
            <text :class="selectedSource ? 'text-[#333]' : 'text-[#999]'">
              {{ selectedSource || "所有来源" }}
            </text>
            <IconFont name="arrow-down" class="text-[24rpx] text-[#999]" />
          </view>
        </view>

        <!-- 日期范围 -->
        <view class="flex-1 min-w-[200rpx]">
          <view
            class="w-full p-[20rpx] border-2 border-[#ddd] rounded-[12rpx] text-[26rpx] bg-white box-border cursor-pointer flex items-center justify-between"
            @click="showDateRangePicker = true"
          >
            <text
              :class="dateRange !== '所有时间' ? 'text-[#333]' : 'text-[#999]'"
            >
              {{ dateRange || "所有时间" }}
            </text>
            <IconFont name="calendar" class="text-[24rpx] text-[#999]" />
          </view>
        </view>

        <!-- 操作按钮组 -->
        <view class="w-full flex gap-[20rpx]">
          <nut-button
            type="primary"
            class="flex-1 text-[28rpx] font-bold"
            @click="handleFilter"
          >
            <IconFont name="search" class="mr-[10rpx]" />
            筛选
          </nut-button>
          <nut-button
            type="default"
            class="flex-1 text-[28rpx] font-bold"
            @click="resetFilter"
          >
            重置
          </nut-button>
        </view>
      </view>
    </view>

    <!-- 候选人列表 -->
    <view
      class="bg-white rounded-[20rpx] mx-[30rpx] mt-[30rpx] shadow-md overflow-hidden"
    >
      <view
        v-for="(candidate, index) in filteredCandidates"
        :key="candidate.id"
        class="p-[30rpx] border-b border-[#eee] transition-all hover:bg-[#f9f9f9]"
      >
        <!-- 上边区域：头像 + 核心信息 -->
        <view class="flex mb-[20rpx]">
          <!-- 头像 -->
          <view
            class="w-[100rpx] h-[100rpx] rounded-full overflow-hidden mr-[30rpx] flex-shrink-0"
          >
            <image
              :src="defaultAvatar"
              mode="widthFix"
              class="w-full h-full object-cover"
            />
          </view>

          <!-- 右边核心信息 -->
          <view class="flex-1 min-w-0">
            <!-- 上区域：姓名 + 状态标签（同行最右侧） -->
            <view class="mb-[10rpx] flex items-center">
              <text class="text-[34rpx] font-bold text-[#333]">
                {{ candidate.name }}
              </text>

              <!-- 状态标签（顶格靠右） -->
              <view
                class="ml-auto px-[18rpx] py-[5rpx] rounded-full text-[22rpx]"
                :class="getStatusClass(candidate.status)"
              >
                {{ getStatusText(candidate.status) }}
              </view>
            </view>

            <!-- 中区域：应聘职位 -->
            <view class="mb-[10rpx]">
              <text class="text-[28rpx] text-[#333]"
                >应聘：{{ candidate.position }}</text
              >
            </view>

            <!-- 下区域：性别年龄 + 学历 + 经验 -->
            <view class="flex flex-wrap gap-[20rpx]">
              <text class="text-[24rpx] text-[#666]"
                >{{ candidate.age }}岁 · {{ candidate.gender }}</text
              >
              <text class="text-[24rpx] text-[#666]"
                >学历：{{ candidate.education }}</text
              >
              <text class="text-[24rpx] text-[#666]"
                >经验：{{ candidate.experience }}</text
              >
            </view>
          </view>
        </view>

        <!-- 下边区域：期望工资 + 操作按钮 -->
        <view
          class="flex items-center justify-between pt-[15rpx] border-t border-[#f0f0f0]"
        >
          <!-- 期望工资 -->
          <view>
            <text class="text-[26rpx] text-[#666]"
              >期望薪资：{{ candidate.expectedSalary }}</text
            >
          </view>

          <!-- 操作按钮组 -->
          <view class="flex gap-[10rpx]">
            <nut-button
              size="mini"
              type="primary"
              @click.stop="handleViewDetail(candidate)"
            >
              查看
            </nut-button>
            <nut-button
              size="mini"
              type="success"
              @click.stop="handleInvite(candidate)"
              :disabled="
                candidate.status !== 'new' && candidate.status !== 'viewed'
              "
            >
              邀请
            </nut-button>
            <nut-button
              size="mini"
              type="danger"
              @click.stop="handleReject(candidate)"
              :disabled="
                candidate.status === 'rejected' ||
                candidate.status === 'invited'
              "
            >
              拒绝
            </nut-button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view
        v-if="filteredCandidates.length === 0"
        class="p-[80rpx] text-center"
      >
        <IconFont name="user" class="text-[120rpx] text-[#ddd] mb-[30rpx]" />
        <text class="text-[28rpx] text-[#999] block">暂无候选人记录</text>
        <nut-button type="primary" class="mt-[30rpx]" @click="resetFilter">
          查看全部
        </nut-button>
      </view>
    </view>

    <!-- 分页 -->
    <view
      v-if="filteredCandidates.length > 0"
      class="flex justify-center mt-[40rpx] mb-[60rpx]"
    >
      <view class="flex items-center gap-[10rpx]">
        <nut-button
          size="small"
          :disabled="currentPage === 1"
          @click="handlePageChange(currentPage - 1)"
        >
          上一页
        </nut-button>

        <view
          v-for="page in visiblePages"
          :key="page"
          class="px-[20rpx] py-[15rpx] border border-[#ddd] rounded-[8rpx] cursor-pointer transition-all"
          :class="
            page === currentPage
              ? 'bg-[#1976d2] text-white border-[#1976d2]'
              : 'bg-white text-[#333]'
          "
          @click="handlePageChange(page)"
        >
          {{ page }}
        </view>

        <nut-button
          size="small"
          :disabled="currentPage === totalPages"
          @click="handlePageChange(currentPage + 1)"
        >
          下一页
        </nut-button>
      </view>
    </view>

    <!-- 职位选择器 -->
    <nut-popup v-model:visible="showPositionPicker" position="bottom" round>
      <nut-picker
        v-model="positionValue"
        :columns="positionOptions"
        title="请选择职位"
        @confirm="onPositionConfirm"
        @cancel="showPositionPicker = false"
      />
    </nut-popup>

    <!-- 状态选择器 -->
    <nut-popup v-model:visible="showStatusPicker" position="bottom" round>
      <nut-picker
        v-model="statusValue"
        :columns="statusOptions"
        title="请选择状态"
        @confirm="onStatusConfirm"
        @cancel="showStatusPicker = false"
      />
    </nut-popup>

    <!-- 来源选择器 -->
    <nut-popup v-model:visible="showSourcePicker" position="bottom" round>
      <nut-picker
        v-model="sourceValue"
        :columns="sourceOptions"
        title="请选择来源"
        @confirm="onSourceConfirm"
        @cancel="showSourcePicker = false"
      />
    </nut-popup>

    <!-- 日期范围选择器 -->
    <nut-popup v-model:visible="showDateRangePicker" position="bottom" round>
      <nut-picker
        v-model="dateRangeValue"
        :columns="dateRangeOptions"
        title="请选择时间范围"
        @confirm="onDateRangeConfirm"
        @cancel="showDateRangePicker = false"
      />
    </nut-popup>

    <!-- 拒绝原因弹窗 -->
    <nut-popup v-model:visible="showRejectReason" position="center" round>
      <view class="p-[40rpx] w-[80vw]">
        <text class="text-[32rpx] font-bold text-[#333] block mb-[20rpx]"
          >拒绝原因</text
        >
        <textarea
          v-model="rejectReason"
          class="w-full border border-[#ddd] rounded-[12rpx] p-[20rpx] min-h-[150rpx] text-[26rpx]"
          placeholder="请输入拒绝原因（选填）"
        />
        <view class="flex gap-[20rpx] mt-[30rpx]">
          <nut-button
            type="default"
            class="flex-1"
            @click="showRejectReason = false"
          >
            取消
          </nut-button>
          <nut-button type="danger" class="flex-1" @click="confirmReject">
            确认拒绝
          </nut-button>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import PageHeader from "@/components/PageHeader.vue";
import pic from "@/assets/pic/tx.jpeg";

// 默认头像
const defaultAvatar = pic;

/**
 * 候选人管理页面（Boss端）
 * @description 显示所有投递简历的候选人，支持筛选、查看详情和操作
 */

// 定义接口
interface CandidateItem {
  id: string;
  name: string;
  avatar?: string;
  age: number;
  gender: "男" | "女";
  position: string;
  expectedSalary: string;
  experience: string;
  education: string;
  source: "app" | "website" | "referral" | "other";
  deliveryTime: string;
  status: "new" | "viewed" | "rejected" | "invited";
  currentCandidate?: boolean; // 用于标记当前操作的候选人
}

// 响应式数据
const totalCount = ref(0);
const pendingCount = ref(0);
const invitedCount = ref(0);
const rejectedCount = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选条件
const selectedPosition = ref("");
const selectedStatus = ref("");
const selectedSource = ref("");
const dateRange = ref("所有时间");

// 选择器相关
const showPositionPicker = ref(false);
const showStatusPicker = ref(false);
const showSourcePicker = ref(false);
const showDateRangePicker = ref(false);
const showRejectReason = ref(false);

const positionValue = ref<string[]>([]);
const statusValue = ref<string[]>([]);
const sourceValue = ref<string[]>([]);
const dateRangeValue = ref<string[]>([]);
const rejectReason = ref("");
const currentCandidate = ref<CandidateItem | null>(null);

// 选项数据
const positionOptions = ref([
  { text: "所有职位", value: "" },
  { text: "SMT技术员", value: "SMT技术员" },
  { text: "品质工程师", value: "品质工程师" },
  { text: "生产主管", value: "生产主管" },
  { text: "技术员", value: "技术员" },
  { text: "操作工", value: "操作工" },
]);

const statusOptions = ref([
  { text: "所有状态", value: "" },
  { text: "新投递", value: "new" },
  { text: "已查看", value: "viewed" },
  { text: "已拒绝", value: "rejected" },
  { text: "已邀请面试", value: "invited" },
]);

const sourceOptions = ref([
  { text: "所有来源", value: "" },
  { text: "App端", value: "app" },
  { text: "官网", value: "website" },
  { text: "推荐", value: "referral" },
  { text: "其他", value: "other" },
]);

const dateRangeOptions = ref([
  { text: "所有时间", value: "all" },
  { text: "今天", value: "today" },
  { text: "近7天", value: "7days" },
  { text: "近30天", value: "30days" },
  { text: "本月", value: "thisMonth" },
  { text: "上月", value: "lastMonth" },
]);

// 模拟候选人数据
const candidateList = ref<CandidateItem[]>([
  {
    id: "1",
    name: "张三",
    avatar:
      "https://img0.baidu.com/it/u=1630300532,2355747067&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
    age: 28,
    gender: "男",
    position: "SMT技术员",
    expectedSalary: "8k-12k",
    experience: "3年",
    education: "大专",
    source: "app",
    deliveryTime: "2025-07-10 14:30",
    status: "new",
  },
  {
    id: "2",
    name: "李四",
    age: 32,
    gender: "女",
    position: "品质工程师",
    expectedSalary: "10k-15k",
    experience: "5年",
    education: "本科",
    source: "website",
    deliveryTime: "2025-07-09 10:15",
    status: "viewed",
  },
  {
    id: "3",
    name: "王五",
    avatar:
      "https://img2.baidu.com/it/u=2532524646,3751465166&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
    age: 25,
    gender: "男",
    position: "SMT技术员",
    expectedSalary: "6k-9k",
    experience: "1年",
    education: "大专",
    source: "referral",
    deliveryTime: "2025-07-08 16:45",
    status: "rejected",
  },
  {
    id: "4",
    name: "赵六",
    age: 35,
    gender: "男",
    position: "生产主管",
    expectedSalary: "15k-20k",
    experience: "8年",
    education: "本科",
    source: "other",
    deliveryTime: "2025-07-07 09:20",
    status: "invited",
  },
  {
    id: "5",
    name: "钱七",
    avatar:
      "https://img1.baidu.com/it/u=1166685356,3664536428&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
    age: 26,
    gender: "女",
    position: "技术员",
    expectedSalary: "7k-10k",
    experience: "2年",
    education: "本科",
    source: "app",
    deliveryTime: "2025-07-06 11:30",
    status: "new",
  },
  {
    id: "6",
    name: "孙八",
    age: 24,
    gender: "男",
    position: "操作工",
    expectedSalary: "5k-7k",
    experience: "应届",
    education: "中专",
    source: "website",
    deliveryTime: "2025-07-05 15:45",
    status: "viewed",
  },
  {
    id: "7",
    name: "周九",
    avatar:
      "https://img0.baidu.com/it/u=3408432135,3642863266&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
    age: 30,
    gender: "男",
    position: "SMT技术员",
    expectedSalary: "9k-13k",
    experience: "4年",
    education: "大专",
    source: "referral",
    deliveryTime: "2025-07-04 08:20",
    status: "rejected",
  },
  {
    id: "8",
    name: "吴十",
    age: 29,
    gender: "女",
    position: "品质工程师",
    expectedSalary: "12k-16k",
    experience: "6年",
    education: "本科",
    source: "other",
    deliveryTime: "2025-07-03 13:15",
    status: "invited",
  },
]);

// 计算属性
const filteredCandidates = computed(() => {
  let filtered = [...candidateList.value];

  // 职位筛选
  if (selectedPosition.value) {
    filtered = filtered.filter(
      (item) => item.position === selectedPosition.value
    );
  }

  // 状态筛选
  if (selectedStatus.value) {
    filtered = filtered.filter((item) => item.status === selectedStatus.value);
  }

  // 来源筛选
  if (selectedSource.value) {
    filtered = filtered.filter((item) => item.source === selectedSource.value);
  }

  // 日期范围筛选
  if (dateRange.value && dateRange.value !== "所有时间") {
    const now = new Date();
    const todayStart = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate()
    ).getTime();

    filtered = filtered.filter((item) => {
      const deliveryDate = new Date(item.deliveryTime).getTime();

      switch (dateRange.value) {
        case "今天":
          return deliveryDate >= todayStart;
        case "近7天":
          return deliveryDate >= todayStart - 7 * 24 * 60 * 60 * 1000;
        case "近30天":
          return deliveryDate >= todayStart - 30 * 24 * 60 * 60 * 1000;
        case "本月":
          const monthStart = new Date(
            now.getFullYear(),
            now.getMonth(),
            1
          ).getTime();
          return deliveryDate >= monthStart;
        case "上月":
          const lastMonth = now.getMonth() - 1;
          const lastMonthStart = new Date(
            lastMonth === -1 ? now.getFullYear() - 1 : now.getFullYear(),
            lastMonth === -1 ? 11 : lastMonth,
            1
          ).getTime();
          const lastMonthEnd = new Date(
            now.getFullYear(),
            now.getMonth(),
            0
          ).getTime();
          return deliveryDate >= lastMonthStart && deliveryDate <= lastMonthEnd;
        default:
          return true;
      }
    });
  }

  return filtered;
});

// 计算总页数
const totalPages = computed(() =>
  Math.ceil(filteredCandidates.value.length / pageSize.value)
);

// 计算可见页码
const visiblePages = computed(() => {
  const pages = [];
  const start = Math.max(1, currentPage.value - 2);
  const end = Math.min(totalPages.value, currentPage.value + 2);

  for (let i = start; i <= end; i++) {
    pages.push(i);
  }

  return pages;
});

// 方法
/**
 * 获取状态样式类
 */
const getStatusClass = (status: string) => {
  const statusMap = {
    new: "bg-[#e3f2fd] text-[#1976d2]",
    viewed: "bg-[#e8f5e9] text-[#388e3c]",
    rejected: "bg-[#ffebee] text-[#d32f2f]",
    invited: "bg-[#fff3e0] text-[#f57c00]",
  };
  return (
    statusMap[status as keyof typeof statusMap] || "bg-[#f5f5f5] text-[#666]"
  );
};

/**
 * 获取状态文本
 */
const getStatusText = (status: string) => {
  const statusMap = {
    new: "新投递",
    viewed: "已查看",
    rejected: "已拒绝",
    invited: "已邀请面试",
  };
  return statusMap[status as keyof typeof statusMap] || "未知";
};

/**
 * 获取来源文本
 */
const getSourceText = (source: string) => {
  const sourceMap = {
    app: "App端",
    website: "官网",
    referral: "推荐",
    other: "其他",
  };
  return sourceMap[source as keyof typeof sourceMap] || "未知";
};

/**
 * 处理筛选
 */
const handleFilter = () => {
  currentPage.value = 1;
  updateStatistics();

  Taro.showToast({
    title: `找到 ${filteredCandidates.value.length} 位候选人`,
    icon: "success",
  });
};

/**
 * 重置筛选条件
 */
const resetFilter = () => {
  selectedPosition.value = "";
  selectedStatus.value = "";
  selectedSource.value = "";
  dateRange.value = "所有时间";
  currentPage.value = 1;
  updateStatistics();
};

/**
 * 更新统计数据
 */
const updateStatistics = () => {
  totalCount.value = filteredCandidates.value.length;
  pendingCount.value = filteredCandidates.value.filter(
    (item) => item.status === "new" || item.status === "viewed"
  ).length;
  invitedCount.value = filteredCandidates.value.filter(
    (item) => item.status === "invited"
  ).length;
  rejectedCount.value = filteredCandidates.value.filter(
    (item) => item.status === "rejected"
  ).length;
};

/**
 * 查看详情
 */
const handleViewDetail = (candidate: CandidateItem) => {
  // 标记为已查看
  if (candidate.status === "new") {
    const index = candidateList.value.findIndex(
      (item) => item.id === candidate.id
    );
    if (index !== -1) {
      candidateList.value[index].status = "viewed";
      updateStatistics();
    }
  }

  // 跳转到详情页或弹窗展示
  Taro.navigateTo({
    url: `/pages/candidateDetail/index?id=${candidate.id}`,
  });
};

/**
 * 邀请面试
 */
const handleInvite = (candidate: CandidateItem) => {
  const index = candidateList.value.findIndex(
    (item) => item.id === candidate.id
  );
  if (index !== -1) {
    candidateList.value[index].status = "invited";
    updateStatistics();

    Taro.showToast({
      title: `已邀请 ${candidate.name} 面试`,
      icon: "success",
    });
  }
};

/**
 * 拒绝候选人
 */
const handleReject = (candidate: CandidateItem) => {
  currentCandidate.value = candidate;
  rejectReason.value = "";
  showRejectReason.value = true;
};

/**
 * 确认拒绝
 */
const confirmReject = () => {
  if (currentCandidate.value) {
    const index = candidateList.value.findIndex(
      (item) => item.id === currentCandidate.value!.id
    );
    if (index !== -1) {
      candidateList.value[index].status = "rejected";
      updateStatistics();

      Taro.showToast({
        title: `已拒绝 ${currentCandidate.value.name}`,
        icon: "success",
      });

      showRejectReason.value = false;
    }
  }
};

/**
 * 处理分页变化
 */
const handlePageChange = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
  }
};

/**
 * 职位确认
 */
const onPositionConfirm = (val: any) => {
  showPositionPicker.value = false;
  if (val.selectedValue && val.selectedValue.length > 0) {
    selectedPosition.value = val.selectedValue[0];
  }
};

/**
 * 状态确认
 */
const onStatusConfirm = (val: any) => {
  showStatusPicker.value = false;
  if (val.selectedValue && val.selectedValue.length > 0) {
    selectedStatus.value = val.selectedValue[0];
  }
};

/**
 * 来源确认
 */
const onSourceConfirm = (val: any) => {
  showSourcePicker.value = false;
  if (val.selectedValue && val.selectedValue.length > 0) {
    selectedSource.value = val.selectedValue[0];
  }
};

/**
 * 日期范围确认
 */
const onDateRangeConfirm = (val: any) => {
  showDateRangePicker.value = false;
  if (val.selectedValue && val.selectedValue.length > 0) {
    const value = val.selectedValue[0];
    // 找到对应的文本
    const option = dateRangeOptions.value.find((item) => item.value === value);
    dateRange.value = option ? option.text : "所有时间";
  }
};

// 生命周期
onMounted(() => {
  updateStatistics();
});
</script>

<style lang="scss">
// 自定义样式
page {
  background-color: #f5f5f5;
}

.grid {
  display: grid;
}

.grid-cols-2 {
  grid-template-columns: repeat(2, 1fr);
}

.md\:grid-cols-4 {
  grid-template-columns: repeat(4, 1fr);
}

.gap-\[20rpx\] {
  gap: 20rpx;
}
</style>
